const BaseService = require('./base.service.js')
const ApiResponse = require('../common/api-response.js')
const UserController = require('./user.controller.js')
const WallpaperDictService = require('./wallpaper-dict.service')
// 在文件顶部添加 WallpaperImageService 的引入
const WallpaperImageService = require('./wallpaper-image.service.js')

class WallpaperSwiperService extends BaseService {
  constructor({ cloudObject }) {
    super({ cloudObject }) // 调用父类构造函数
    this.collectionName = 'iss-wallpaper-swiper'
    this.userController = new UserController(cloudObject)
    this.wallpaperDictService = new WallpaperDictService({ cloudObject })
	// 注入 WallpaperImageService 实例
	this.wallpaperImageService = new WallpaperImageService({cloudObject})
  }

  // 获取集合引用
  get collection() {
    return this.db.collection(this.collectionName)
  }

  /**
   * 构建JQL简单查询条件
   * @param {Object} query - 查询参数
   * @returns {Object} JQL查询条件
   */
  _buildWhereConditions(query) {
    const whereConditions = {}

    if (query.description) {
      whereConditions.description = new RegExp(query.description, 'i')
    }

    // if (query.sort) {
    //   whereConditions.sort = query.sort
    // }

    // if (query.target) {
    //   whereConditions.target = query.target
    // }

    // if (query.picurl) {
    //   whereConditions.picurl = query.picurl
    // }

    // if (query.url) {
    //   whereConditions.url = query.url
    // }
	
	// 增加推荐级别查询条件
	  if (query.type) {
	    if (Array.isArray(query.type)) {
	      whereConditions.type = {
	        $in: query.type
	      }
	    } else {
	      whereConditions.type = query.type
	    }
	  }

    if (query.enable!== undefined) {
      whereConditions.enable = query.enable
    }

    if (Array.isArray(query.createTime) && query.createTime.length === 2) {
      whereConditions.createTime = {
        $gte: query.createTime[0],
        $lte: query.createTime[1]
      }
    }

    if (Array.isArray(query.updateTime) && query.updateTime.length === 2) {
      whereConditions.updateTime = {
        $gte: query.updateTime[0],
        $lte: query.updateTime[1]
      }
    }

    return whereConditions
  }

   /**
     * 分页查询轮播图列表
     * @param {Object} query - 查询参数
     * @returns {ApiResponse} 统一响应格式
     */
    async getList(query = {}) {
      try {
        // 对权限进行校验
        await this.userController.hasPermission('wsr', 'allin', 'permission')
  
        this.dbJQL = uniCloud.databaseForJQL()
        const whereConditions = this._buildWhereConditions(query)
        const orderFiled = query.orderFiled || 'updateTime'
        const orderDirection = query.orderDirection || 'desc'
  
        const { total } = await this.collection.where(whereConditions).count()
  
        // 执行查询
        const swipers = await this.dbJQL.collection(this.collectionName)
          .where(whereConditions)
          .orderBy(orderFiled, orderDirection)
          .skip((query.page - 1) * query.pageSize)
          .limit(query.pageSize)
          .getTemp()
  
        const users = this.dbJQL.collection('uni-id-users').field('_id, nickname').getTemp()
  
        const cb = await this.dbJQL.collection(swipers, users)
          .get()
  
        return ApiResponse.success({
          total,
          list: cb.data
        })
      } catch (e) {
        console.error('获取轮播图列表失败:', e)
        return ApiResponse.serverError(ApiResponse.ErrorMessage.SERVICE_ERROR + '-' + e)
      }
    }
  
    /**
     * 根据id获得对应轮播图
     * @param {string} id - 轮播图ID
     * @returns {ApiResponse} 统一响应格式
     */
    async doc(id) {
      try {
        if (!id) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
        }
        // 对权限进行校验
        await this.userController.hasPermission('wsr', 'allin', 'permission')
  
        const response = await this.collection.doc(id).get()
  
        if (response.data && response.data.length === 1) {
          return ApiResponse.success(response.data[0])
        }
        return ApiResponse.notFound(ApiResponse.ErrorMessage.SWIPER_NOT_FOUND)
      } catch (e) {
        console.error('获取轮播图失败:', e)
        return ApiResponse.serverError('获取轮播图失败:' + e)
      }
    }
  
    /**
     * 新增轮播图
     * @param {Object} data - 轮播图数据
     * @returns {ApiResponse} 统一响应格式
     */
    async add(data) {
      try {
        if (!data ||!data.picurl) {
          return ApiResponse.badRequest('图片地址和排序不能为空');
        }
  
        // 对权限进行校验
        await this.userController.hasPermission('wsa', 'allin', 'permission')
        // 进一步从数据库中获取当前用户的信息
        const userInfoDetail = await this.userController.getUserInfoDBDetal(this.userController.userInfo.uid);
  
        // 准备基础数据
        const baseInsertData = {
          _uid: userInfoDetail._id,
          target: data.target ||'self',
          url: (data.url || '').trim(),
          type: data.type || '',
          description: (data.description || '').trim(),
          enable:!!data.enable || true,
          updateTime: Date.now(),
		  creatTime: Date.now()
        };
  
        // 插入数据
        const result = await this.collection.add({
         ...baseInsertData,
		 ...data
        });
  
        if (result.id) {
          return ApiResponse.success({
            id: result.id
          }, `成功创建轮播图记录`);
        } else {
          return ApiResponse.serverError('创建轮播图失败');
        }
      } catch (e) {
        console.error('创建轮播图失败:', e);
        return ApiResponse.serverError('创建轮播图失败: ' + e.message);
      }
    }
  
    /**
     * 批量删除轮播图
     * @param {Array<string>} ids - 要删除的ID数组
     * @returns {ApiResponse} 统一响应格式
     */
    async remove(ids) {
      try {
        if (!Array.isArray(ids) || ids.length === 0) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.IDS_REQUIRED)
        }
        await this.userController.hasPermission('wsd', 'allin', 'permission')
		
		const res = await this.collection.where({_id: this.dbCmd.in(ids)}).get()
		const cloudIds = res.data.map(item=>item.picurl)
  
        const result = await this.collection.where({ _id: this.dbCmd.in(ids) }).remove()
		
		try{
			// 调用 WallpaperImageService 的 deleteImage 方法删除图片
			if (cloudIds.length > 0) {
				const deleteResult = this.handleApiResponse(() => this.wallpaperImageService.deleteImage(cloudIds))
			}
		} catch(e) {
		  console.log('图片删除失败:' + e)
		}
  
        if (result.deleted === 0) {
          return ApiResponse.notFound(ApiResponse.ErrorMessage.SWIPER_NOT_FOUND)
        }
  
        return ApiResponse.success({
          deleted: result.deleted
        }, '删除成功')
      } catch (e) {
        console.error('删除轮播图失败:', e)
        return ApiResponse.serverError('删除轮播图失败:' + e)
      }
    }
  
    /**
     * 更新轮播图信息
     * @param {Object} data - 包含id和更新数据
     * @returns {ApiResponse} 统一响应格式
     */
    async update(data = {}) {
      try {
        if (!data ||!data._id) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
        }
  
        // 对权限进行校验
        await this.userController.hasPermission('wse', 'allin', 'permission')
        // 进一步从数据库中获取当前用户的信息
        const userInfoDetail = await this.userController.getUserInfoDBDetal(this.userController.userInfo.uid);
  
        // 提取需要更新的数据
        const { _id, updateTime, ...updateData } = data
  
        updateData._uid = userInfoDetail._id
        updateData.nickname = userInfoDetail.nickname
  
        // 执行更新
        const result = await this.collection.where({ _id }).update(updateData)
  
        return ApiResponse.success({
          updated: result.updated
        }, '轮播图更新成功')
      } catch (e) {
        console.error('更新轮播图失败:', e)
        return ApiResponse.serverError('更新轮播图失败: ' + e.message)
      }
    }
  
    /**
     * 切换bool类型字段状态
     * @param {string} id - 轮播图ID
     * @param {string} fieldName - 字段名
     * @returns {ApiResponse} 统一响应格式
     */
    async columnToggle(id, fieldName) {
      try {
        if (!id) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
        }
  
        if (!fieldName) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.PARAM_INCOMPLETE)
        }
  
        // 对权限进行校验
        await this.userController.hasPermission('wse', 'allin', 'permission')
  
        // 获取当前状态
        const doc = await this.collection.doc(id).get()
        if (!doc.data ||!doc.data.length) {
          return ApiResponse.notFound(ApiResponse.ErrorMessage.SWIPER_NOT_FOUND)
        }
  
        // 取反状态
        const currentValue = doc.data[0][fieldName]
        const params = { [fieldName]:!currentValue }
  
        const result = await this.collection.doc(id).update(params)
  
        if (result.updated === 0) {
          return ApiResponse.notFound('更新失败')
        }
  
        return ApiResponse.success({
          updated: result.updated
        }, '状态切换成功')
      } catch (e) {
        console.error('切换状态失败:', e)
        return ApiResponse.serverError('切换状态失败:' + e)
      }
    }
  
    /**
     * 获取轮播图类型的选项
     * @param {string} type - 数据字典类型
     * @returns {Promise<ApiResponse>} 包含选项的响应
     */
    async getTypeOptions(type) {
      try {
        return this.wallpaperDictService.getOptionsByType(type)
      } catch (e) {
        console.error('获取轮播图类型选项失败:', e)
        return ApiResponse.serverError('获取轮播图类型选项失败:' + e)
      }
    }
}

module.exports = WallpaperSwiperService